define(function(require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    
    
    require('../su/accordion/oaTabCtrl');
    
    
    //引入jstree
    $.widget('rk.favoritesPanelCtrl', $.rk.oaPanelCtrl, {
        _create: function () {
            var me = this;
            var elem = me.element;
            //1，模板文件请在WEB-INFO/templates/oa中追加
            //2，请在src/resources/sub-deps/oa中引入
            //3，如下所示，调用rk.template方法生成html
            me._listeners();
        },
        _listeners: function () {
            var me = this;
            var elem = me.element;
            me._favorites_introduce_click_listener();
            me._favorites_introduce_close_listener();
            me._favorites_create_from_inner_panel_click_listener();
        },
        //init方法中，用来初始化数据
        _init: function () {
            var me = this;
            var elem = me.element;
            me.loaddata("favorites");
        },
        _favorites_introduce_click_listener: function() {
            var me = this;
            var elem = me.element;
            elem.on("click", "[act='favorites-introduce']", function() {
                me._showFavoritesIntroduce();
            });
        },
        _favorites_create_from_inner_panel_click_listener: function() {
            var me = this;
            var elem = me.element;
            elem.on("click", "[act='create_from_favorites_inner_panel']", function() {
                require.async(["./content/favoritesCreateNewPanelCtrl"], function() {
                    rk.dialog({
                        title: rk.i18n('ADD') + rk.i18n('OA_FAVORITES'),
                        success: function (contentElem) {
                            contentElem.favoritesCreateNewPanelCtrl();
                        },
                        close: function() {
                            me.loaddata("favorites");
                        },
                        footer: ['cancel', {
                            act: 'ok', visible: true, text: rk.i18n('SAVE')
                        }]
                    });
                });
            });
        },
        _favorites_introduce_close_listener: function() {
            var me = this;
            var elem = me.element;
            elem.on("click", "[act='favorites_introduce_close']", function() {
                me._closeFavoritesIntroduce();
            });
        },
        _showFavoritesIntroduce: function() {
            var me = this;
            var elem = me.element;
            var html = require('oa/tmpl/favorites/tpl_favorites_introduce.tpl');
            elem.append(html);
        },
        _closeFavoritesIntroduce: function() {
            var me = this;
            var elem = me.element;
            elem.find('[act="favorites_introduce_content"]').hide();
        },
        _favorites_show_all_users_added_blur_listener: function() {
            var me = this;
            var elem = me.element;
            var inner = elem.find('[act="show_all_users_added_blur"]');
            $.each(inner, function(i, item) {
                var content = $(item).attr('content');
                $(item).beTip({title:content, dir:"top"});
            });
        },
        _favorites_row_edit_listener: function(json) {
            var me = this;
            var elem = me.element;
            var opt = this.options;
            var row = elem.find('[act="edit_favorites_row"]');

            var usersAdded = json.usersAdded;

            $.each(row, function(i, item) {
                $(item).on("click", function() {
                    var id = $(item).attr('id');

                    //var name = $(item).attr('name');

                    var m = $(item).parent().parent();
                    var name = m.find('.group_name')[0].innerText;

                    var userIdsAdded = $(item).attr('userIdsAdded');

                    var userCount = 0;
                    if (userIdsAdded) {
                        userCount = userIdsAdded.split(',').length;
                    }
                    if (id) {
                        var cuurPageNo = 1;
                        if (opt.pageNo) {
                            cuurPageNo = opt.pageNo;
                        }

                        require.async(["./content/favoritesCreateNewPanelCtrl"], function() {
                            rk.dialog({
                                title: rk.i18n('EDIT') + rk.i18n('OA_FAVORITES'),
                                success: function (contentElem) {
                                    var params = {favoritesId: id, name: name, userIdsAdded: userIdsAdded, usersAdded: usersAdded};
                                    contentElem.favoritesCreateNewPanelCtrl({params: params});
                                },
                                close: function() {
                                    me.loaddata("favorites", {pageNo:cuurPageNo,pageSize:20});
                                },
                                footer: ['cancel', {
                                    act: 'ok', visible: true, text: rk.i18n('SAVE')
                                }]
                            });
                        });
                    }
                });
            });
        },
        _favorites_row_delete_listener: function() {
            var me = this;
            var elem = me.element;
            var row = elem.find('[act="delete_favorites_row"]');
            $.each(row, function(i, item) {
                $(item).on("click", function() {
                    var id = $(item).attr('id');
                    if (id) {
                        rk.confirm(rk.i18n('FAVORITES_CONFIRM_DELETE'),{okText:rk.i18n('DELETE')}, function(){
                            me._deleteFavoritesDetail(id);
                        }, function() {

                        });
                    }
                });
            });
        },
        loaddata: function (type, param) {
            var me = this;
            var elem = me.element;

            if (!param) {
                param = {pageNo:1,pageSize:20};
            }
            if (type === "favorites") {
                rk.post("/json/oa_favorites/favorites_list.action", param, function(json) {
                    if (0 === json.status) {
                        var wholeTemp = require('oa/tmpl/favorites/tpl_favorites_favorites_whole.tpl');
                        var wholeHtml = rk.templateText(wholeTemp, json);
                        elem.html(wholeHtml);
                        elem.find('[act="favorites_scroll"]').beScroll();

                        if (json.favoritesList && json.favoritesList.length > 0) {
                            var favoritesList = json.favoritesList;
                            var users = json.usersAdded;

                            var listHtml = "";
                            var temp = require('oa/tmpl/favorites/tpl_favorites_favorites_table_row.tpl');
                            var i = 0
                            $.each(favoritesList, function (i, dataJson) {
                                if (dataJson.userIdsAdded) {
                                    dataJson.userCount = dataJson.userIdsAdded.split(",").length;

                                    var userNames = me.getUserNames(dataJson.userIdsAdded, users);
                                    if (!("" == userNames)) {
                                        dataJson.userNames = userNames.substring(0, userNames.length - 1);
                                    }
                                }
                                listHtml += rk.templateText(temp, dataJson);
                            });

                            elem.find('[act="favorites-list-content"]').html(listHtml);

                            elem.find('[act="favorites_page_footer"]').show();

                            elem.find('[act="favorites_pagination_info"]').rkPaging({
                                pagenum: json.pageNo,  //（可选）当前页数，默认1
                                pagesize: json.pageSize,  //（可选）当前每页显示条数，默认20
                                rowscount: json.dataCount, //所有数据数
                                onChange: function (pagenum) {
                                    var params = param;
                                    params.pageNo = pagenum;
                                    params.pageSize = json.pageSize;

                                    var opt = me.options;
                                    opt.pageNo = pagenum;
                                    me.loaddata(type, params)
                                }
                            });

                            me._favorites_row_edit_listener(json);
                            me._favorites_row_delete_listener();
                            me._favorites_show_all_users_added_blur_listener();
                        } else {
                            var temp = require('oa/tmpl/favorites/tpl_favorites_none.tpl');
                            var emptyHtml = rk.templateText(temp, {text: rk.i18n('同事收藏夹，将常用人员分组')});
                            elem.find('[act="favorites-list-content"]').html(emptyHtml);

                            elem.find('[act="favorites_page_footer"]').hide();
                        }
                    }
                });
            }
        },

        _deleteFavoritesDetail: function(id) {
            var me = this;
            var elem = me.element;
            $.post("/json/oa_favorites/delete_favorites.action", {favoritesId: id}, function(json) {
                if (0 === json.status && json.success) {
                    var rows = elem.find('[act="favorites_row_content"]');
                    $.each(rows, function(i, item) {
                        if (id === $(item).attr('id')) {
                            $(item).remove();
                        }
                    });
                }
            });
        },

        getUserNames : function (myIds, users) {
            var me = this;
            var ids = myIds.split(",");
            var res = "";
            $.each(ids, function(i, id) {
                res += me.getUserName(id, users) + "、";
            });

            return res;
        },

        getUserName : function (myId, users) {
            var name = "";
            $.each(users, function (i, user) {
                if (user.id == myId) {
                    name = user.name;
                    return;
                }
            });
            return name;
        }

    })
});